package com.linkoog.devtools.code_generator.wizard.code_database.ui.database.dialog.datasource.panel;

import com.linkoog.devtools.code_generator.database.domain.ConnectionInfo;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;

public class DatasourceTreeCellRender extends DefaultTreeCellRenderer {


    private static final long serialVersionUID = -6564861041507376828L;

    /**
     * 重写父类DefaultTreeCellRenderer的方法
     */
    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean isLeaf, int row, boolean hasFocus) {
        // 选中
        if (selected) {
            setForeground(getTextSelectionColor());
        }
        /*else {
            setForeground(getTextNonSelectionColor());
        }*/

        DefaultTreeCellRenderer tempCellRenderer = new DefaultTreeCellRenderer();

        // TreeNode
        DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) value;
        Object obj = treeNode.getUserObject();
        if (obj instanceof ConnectionInfo) {
            ConnectionInfo info = (ConnectionInfo) obj;
            tempCellRenderer.setOpenIcon(info.getDbType().getIcon());
            tempCellRenderer.setClosedIcon(info.getDbType().getIcon());
            tempCellRenderer.setLeafIcon(info.getDbType().getIcon());

            StringBuilder builder = new StringBuilder(150);
            builder.append("<html>")
                    .append("<font color=\"#7F7F7F\">[").append(handlerName(info.getName())).append("]</font>")
                    .append("&nbsp;&nbsp;");

            builder.append(info.getHost()).append("@").append(info.getDatabase());
            builder.append("</html>");

            return tempCellRenderer.getTreeCellRendererComponent(tree, info.getName(), selected, expanded, false, row, hasFocus);
        }
        else {
            return tempCellRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, false, row, hasFocus);
        }
    }

    private String handlerName(String name) {
        int total = 15;
        if (name.length() >= total){
            name = name.substring(0, total - 4) + "...";
        }else {
            /*int padLen = total - methodName.length();
            StringBuilder temp = new StringBuilder(padLen);
            for (int i = 1; i <=  padLen; i++) {
                temp.append("&nbsp;");
            }
            methodName = methodName + temp.toString();*/
        }
        return name;
    }


}
